import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, Image, StyleSheet, Alert, ActivityIndicator, Platform } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import { Colors } from '../constants/colors';
import { fileService } from '../services';

interface Props {
  label: string;
  subtitle?: string; // 副标题
  uri?: string | null;
  onPick?: () => void; // 可覆蓋內置選圖
  onChangeUri?: (uri: string | null) => void; // 回傳給父組件
  onUploadComplete?: (ossUrl: string) => void; // 上传完成回调，返回OSS地址
  tipText?: string;
  showRightTip?: boolean;
}

export default function UploadField({ label, subtitle, uri, onPick, onChangeUri, onUploadComplete, tipText = '上傳圖片', showRightTip = false }: Props) {
  const [localUri, setLocalUri] = useState<string | null>(uri ?? null);
  const [uploading, setUploading] = useState(false);

  useEffect(() => { 
    setLocalUri(uri ?? null); 
  }, [uri]);

  // 验证URI是否有效（特别是在移动端）
  const isValidUri = (uriToCheck: string | null): boolean => {
    if (!uriToCheck) return false;
    
    // 在移动端，检查是否是有效的URI格式
    if (Platform.OS !== 'web') {
      // 移动端的本地URI通常以file://开头，或者是网络URL
      return uriToCheck.startsWith('file://') || 
             uriToCheck.startsWith('http://') || 
             uriToCheck.startsWith('https://') ||
             uriToCheck.startsWith('content://'); // Android content URI
    }
    
    return true; // Web端直接返回true
  };

  const openPicker = async () => {
    try {
      const perm = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (perm.status !== 'granted') {
        Alert.alert('權限不足', '需要相冊權限以選擇圖片');
        return;
      }

      const res = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ['images'],
        quality: 0.8,
        allowsEditing: true
      });

      if (!res.canceled && res.assets && res.assets.length > 0) {
        const imageUri = res.assets[0].uri;
        
        // 如果有上传回调，则直接上传到OSS，不先设置本地URI
        if (onUploadComplete) {
          // 先显示本地图片预览
          setLocalUri(imageUri);
          await uploadToOss(imageUri);
        } else {
          // 如果不需要上传，直接设置本地URI
          setLocalUri(imageUri);
          onChangeUri?.(imageUri);
        }
      }
    } catch (e) {
      console.warn('pick image error', e);
      Alert.alert('出錯了', '選擇圖片失敗，請重試');
    }
  };

  // 上传到OSS
  const uploadToOss = async (imageUri: string) => {
    const previousUri = localUri; // 保存之前的URI，用于错误恢复
    setUploading(true);
    
    try {
      // 创建FormData
      const formData = new FormData();

      // 在Web端和移动端处理文件的方式不同
      if (Platform.OS === 'web') {
        // Web端处理
        const response = await fetch(imageUri);
        const blob = await response.blob();
        // 创建File对象
        const file = new File([blob], 'image.jpg', { type: 'image/jpeg' });
        formData.append('file', file);
      } else {
        // 移动端处理
        formData.append('file', {
          uri: imageUri,
          type: 'image/jpeg',
          name: 'image.jpg',
        } as any);
      }

      console.log('开始上传文件到OSS...');
      const result = await fileService.uploadFile(formData);
      console.log('文件上传成功:', result);

      // 上传成功后，更新本地URI为OSS URL，确保图片能正确回显
      setLocalUri(result.url);
      onChangeUri?.(result.url);
      onUploadComplete?.(result.url);
      Alert.alert('成功', '圖片上傳成功');
    } catch (error: any) {
      console.error('图片上传失败:', error);
      // 上传失败时恢复到之前的状态
      setLocalUri(previousUri);
      onChangeUri?.(previousUri);
      Alert.alert('上傳失敗', error.message || '圖片上傳失敗，請重試');
    } finally {
      setUploading(false);
    }
  };

  const handlePress = () => {
    if (onPick) return onPick();
    openPicker();
  };

  return (
    <View style={styles.cardContainer}>
      <View style={styles.leftRow}>
        <View style={styles.labelContainer}>
          <Text style={styles.leftLabel}>{label}</Text>
          {subtitle && <Text style={styles.subtitle}>{subtitle}</Text>}
        </View>
        <TouchableOpacity
          style={[styles.box, { flex: 1 }, uploading && styles.uploadingBox]}
          onPress={handlePress}
          activeOpacity={0.8}
          disabled={uploading}
        >
          {uploading ? (
            <View style={styles.uploadingContainer}>
              <ActivityIndicator size="small" color={Colors.primary} />
              <Text style={styles.uploadingText}>上傳中...</Text>
            </View>
          ) : (localUri && isValidUri(localUri)) ? (
            <Image 
              source={{ uri: localUri }} 
              style={styles.img}
              onError={(error) => {
                console.warn('图片加载失败:', error.nativeEvent.error);
                // 图片加载失败时清除URI
                setLocalUri(null);
                onChangeUri?.(null);
              }}
            />
          ) : (
            <View style={styles.placeholder}>
              <Ionicons name="image-outline" size={20} color={Colors.gray[500]} />
              <Text style={styles.tip}>點擊上傳</Text>
            </View>
          )}
          {showRightTip && (
            <View style={styles.rightTip}>
              <Text style={styles.rightTipText}>{tipText}</Text>
              <Ionicons name="camera" size={16} color={Colors.primary} style={{ marginLeft: 6 }} />
            </View>
          )}
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  cardContainer: { backgroundColor: Colors.white, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, borderWidth: 1, borderColor: Colors.gray[200] },
  leftRow: { flexDirection: 'row', alignItems: 'center' },
  labelContainer: { width: 86 },
  leftLabel: { color: Colors.gray[600], fontSize: 14 },
  subtitle: { color: Colors.gray[500], fontSize: 12, marginTop: 2 },
  box: { height: 120, backgroundColor: Colors.white, borderRadius: 10, overflow: 'hidden' },
  placeholder: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  tip: { color: Colors.gray[500], marginTop: 6 },
  img: { width: '100%', height: '100%', resizeMode: 'cover' },
  rightTip: { position: 'absolute', right: 10, top: 10, backgroundColor: 'rgba(255,255,255,0.9)', borderRadius: 16, paddingHorizontal: 10, paddingVertical: 6, flexDirection: 'row', alignItems: 'center' },
  rightTipText: { color: Colors.primary, fontWeight: '700' },
  uploadingBox: {
    opacity: 0.7,
  },
  uploadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  uploadingText: {
    marginTop: 8,
    fontSize: 14,
    color: Colors.primary,
  },
});

